const express =  require('express')
const http = require('http')
const updateCompiler = require('./utils/updateCompiler.js')
const webpackDevMiddleWare = require('../../webpack-middleware')
class Server {
    constructor(compiler, devServerArgs) {
        this.compiler = compiler
        this.devServerArgs = devServerArgs
        updateCompiler(compiler)
        this.setUpHooks(compiler)
        this.setupApp()
        this.routes()
        this.setUpDevMiddleware(compiler)
        this.createServer()
    }
    routes() {
      if(this.devServerArgs.contentBase) {
        this.setupApp.use(express.static(this.devServerArgs.contentBase))
      }
    }
    /**
     * express中间件的源码先创建一个路由服务然后再去监听路由
     * app.listen = function listen() {
            var server = http.createServer(this);
            return server.listen.apply(server, arguments);
        };
     */
    setupApp() {
        // this.app不是一个服务，本身就是一个路由中间件，本身他提供路由服务的
        this.app = express()
    }
    createServer() {
        this.server = http.createServer(this.app)
    }
    listen(port, host,callback) {
        //这里是一个服务
        this.server.listen(port, host,callback)
    }
    setUpHooks() {
        //监听编译成功的事件 当webpack完成一次完整的编译之后，会触发done这个钩子函数的回调函数执行
        this.compiler.hooks.done.tap('webpack-dev-server',(stats)=>{ // stats 描述哪些文件产生了，是一个清单
            this._stats = stats
            // console.log(stats, 'setUpHooks')
        })
    }
    setUpDevMiddleware(compiler) {
        this.middleware = webpackDevMiddleWare(compiler)
        this.app.use(this.middleware)
    } 
}
module.exports = Server;